<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use TheSeer\Tokenizer\Exception;

class MigrateSingleTopics extends Command
{
    protected $signature   = 'migrate:single-topics {sheet*}';
    protected $description = '迁移关联数据';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        set_time_limit(0);

        $sheet = $this->argument('sheet');

        $hasPaperIds = DB::connection('test')->table('papers')
                        ->select('id')
                        ->pluck('id')
                        ->toArray();

        $paperIds = DB::connection('test')->table('import')
                      ->whereIn('sheet', $sheet)
                      ->where('status', 0)
                      ->pluck('paper_id')
                      ->toArray();
        // $paperIds = ['2c9a2ebc7230085101724f1aa6ca3aa9'];

        $singleTopicIds = DB::table('single_topics_paper')
                            ->whereIn('paper_id', $paperIds)
                            ->whereNotIn('paper_id', $hasPaperIds)
                            ->pluck('single_topic_id')
                            ->toArray();

        $singleTopicIds = array_unique($singleTopicIds);
        $singleTopics = DB::table('single_topics')
                          ->whereIn('id', $singleTopicIds)
                          ->get();

        try {
            foreach ( $paperIds as $paperId ) {
                $this->insertPaperRecords('papers', $paperId);
            }
            foreach ( $singleTopics as $singleTopic ) {
                $exists = DB::connection('test')->table('single_topics')
                            ->select('id')
                            ->where('id', $singleTopic->id)
                            ->first();

                if (! $exists) {
                    DB::connection('test')->table('single_topics')->insert((array)$singleTopic);

                    $this->insertRelatedRecords('single_topic_option', $singleTopic->id);

                    $this->insertRelatedRecords('single_topics_knowledge_points', $singleTopic->id);

                    $this->insertRelatedRecords('single_topics_source', $singleTopic->id);

                    $this->insertRelatedRecords('single_topics_use_zone', $singleTopic->id);
                }
            }

            DB::connection('test')->table('import')
              ->whereIn('paper_id', $paperIds)
              ->update(['status' => 1]);

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            $this->error('失败:'.$exception->getMessage());

            return false;
        }


        $this->info('Migration completed successfully.');
    }

    protected function insertRelatedRecords($table, $singleTopicId)
    {
        $relatedRecords = DB::table($table)
                            ->where('single_topic_id', $singleTopicId)
                            ->get();

        foreach ( $relatedRecords as $record ) {
            DB::connection('test')->table($table)->insert((array)$record);
        }
    }

    protected function insertPaperRecords($table, $paperId)
    {
        $relatedRecords = DB::table($table)
                            ->where('id', $paperId)
                            ->first();
        if (! $relatedRecords) {
            return true;
        }
        $paper = DB::connection('test')->table($table)
                   ->select('id')
                   ->where('id', $paperId)
                   ->first();
        if ($paper) {
            return true;
        }
        DB::connection('test')->table($table)->insert((array)$relatedRecords);

        $this->insertPaperRelatedRecords('paper_area', $paperId);

        $this->insertPaperRelatedRecords('single_topics_paper', $paperId);
    }

    protected function insertPaperRelatedRecords($table, $paperId)
    {
        $relatedRecords = DB::table($table)
                            ->where('paper_id', $paperId)
                            ->get();

        foreach ( $relatedRecords as $record ) {
            DB::connection('test')->table($table)->insert((array)$record);
        }
    }

}
